package com.qingcloud.adminbackend.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * HTTP 请求工具类
 */
public class OKHttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(OKHttpUtil.class);

    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    private static OkHttpClient okHttpClient;

    static {
        okHttpClient = new OkHttpClient.Builder().connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .build();
    }

    /**
     * get请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String httpGet(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        return call(request);
    }

    /**
     * post 请求
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String httpPost(String url, String json) {
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return call(request);
    }

    /**
     * post 请求
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String httpPostAndHeader(String url, String json) {
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent","Mozilla")
                .post(requestBody)
                .build();
        return call(request);
    }
    /**
     * 发起请求
     */
    public static String call(Request request) {
        ResponseBody response;
        try {
            response = okHttpClient.newCall(request).execute().body();
            if (response != null) {
                return response.string();
            }
        } catch (Exception e) {
            logger.error("OKHttp error, {}", e);
        }
        return null;
    }
}
